package com.blb.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIODemo {

    public static void read(String path){
        //创建文件输入流
        try(FileInputStream in = new FileInputStream(path);
        //获得文件通道
            FileChannel channel = in.getChannel();
        ){
            //创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(100);
            int len = 0;
            //循环读取数据到缓冲区
            while((len = channel.read(buffer)) != -1){
                //把缓冲区从写状态切换到读状态
                buffer.flip();
                //从缓冲区读取数据，打印出来
                String s = new String(buffer.array(), 0, len, "utf-8");
                System.out.print(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void write(String path,String content){
        try(FileOutputStream out = new FileOutputStream(path);
            FileChannel channel = out.getChannel();
        ){
            //把数组包装到缓冲区中
            ByteBuffer buffer = ByteBuffer.wrap(content.getBytes());
            channel.write(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        read("D:\\项目描述.txt");
        write("D:\\xxx.txt","哈哈哈，这就是NIO？");
    }
}
